package com.sfx.concurrent.demo.concurrent.ScheduledTask;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-27
 * Time: 16:30
 */
@Slf4j(topic = "c.TestScheduledTask")
public class TestScheduledTask {

    /**
     * 每周四18:00:00来执行定时任务
     * @param args
     */
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        //period : 一周的间隔时间-->因为是每周四
        //long period = 1000*60*60*24*7;
        long period = 1000;
        //initialDelay :与下周四的时间差
        //计算当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("now : " +now);
        //设置到18:00:00
        LocalDateTime time = now.withHour(17).withMinute(1).withSecond(0).withNano(0).with(DayOfWeek.FRIDAY);
        System.out.println("time : " +time);
        if(now.compareTo(time)>0) {//当前比周四大,就在加一周
            time = time.plusWeeks(1);
        }
        long initialDelay = Duration.between(now, time).toMillis();
        System.out.println(initialDelay);
        pool.scheduleAtFixedRate(()->{
            log.debug("running");
        },initialDelay,period,TimeUnit.MILLISECONDS);
    }
}
